//
//  AliyunUploadBlock.m
//  HiCar
//
//  Created by 丁一 on 2019/2/10.
//  Copyright © 2019 丁一. All rights reserved.
//

#import "AliyunUploadBlock.h"
#import "HiJonesClass.h"

@implementation AliyunUploadBlock

+ (void)AliyunUploadimg:(UIImage *)image imgname:(NSString *)imgname finished:(void(^)(OSSTask *task,NSString *imgurl))block{
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    put.bucketName = OSS_BUCKET_PUBLIC;
    put.objectKey = imgname;
    
    UIImage *fenzheng001 = [HiJonesClass compressImage:image toByte:350];
    
    NSData * imageData;
    imageData = UIImageJPEGRepresentation(fenzheng001,1);
    
    put.uploadingData = imageData; // 直接上传NSData
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    OSSTask * putTask = [[JonesSingle instance].client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            NSLog(@"upload object success!");
            
            NSString *logourl = [NSString stringWithFormat:@"%@/%@",OSS_IMG_ENDPOINT,imgname];
            
            block(nil,logourl);
            
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
            [SVProgressHUD showErrorWithStatus:@"图片服务器错误"];
            
            block(task,nil);
        }
        return nil;
    }];
    // 可以等待任务完成
    //[putTask waitUntilFinished];
}

+ (void)AliyunDelete:(NSString *)imgname finished:(void(^)(OSSTask *task))block{
    
    OSSDeleteObjectRequest * delete = [OSSDeleteObjectRequest new];
    delete.bucketName = OSS_BUCKET_PUBLIC;
    delete.objectKey = imgname;
    
    OSSTask * deleteTask = [[JonesSingle instance].client deleteObject:delete];
    
    [deleteTask continueWithBlock:^id(OSSTask *task) {
        block(task);
        return nil;
    }];
    
    // [deleteTask waitUntilFinished];
}

@end
